package com.example;

public class DeadlockDemo {

    public static void main(String[] args) {
        Deadlock deadlock = new Deadlock("1", "2");
        new Thread(() -> {
            deadlock.run();
        }, "ThreadA").start();

        new Thread(() -> {
            deadlock.run2();
        }, "ThreadB").start();
    }
}

class Deadlock implements Runnable {
    private String dataA;
    private String dataB;

    public Deadlock(String dataA, String dataB) {
        this.dataA = dataA;
        this.dataB = dataB;
    }

    @Override
    public void run() {
        synchronized (dataA) {
            System.out.println(Thread.currentThread().getName() + "\t 获取dataA:" + dataA + ",尝试获取dataB:" + dataB);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (dataB) {
                System.out.println(Thread.currentThread().getName() + "\t 获取了dataB:" + dataB);
            }
        }
    }

    public void run2() {
        synchronized (dataB) {
            System.out.println(Thread.currentThread().getName() + "\t 获取dataB:" + dataA + ",尝试获取dataA:" + dataB);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (dataA) {
                System.out.println(Thread.currentThread().getName() + "\t 获取了dataA:" + dataB);
            }
        }
    }
}